package castledefense.logic.pathfinding;

import java.util.ArrayList;

import pathfinding.core.Path;
import castledefense.data.GameData;
import castledefense.util.Log;

public class PathfindingThreadBuilding implements Runnable{
	
	private ArrayList<PositionBuilding> buildingList = new ArrayList<PositionBuilding>();
	private ArrayList<PositionBuilding> buildingList2 = new ArrayList<PositionBuilding>();
	
	private LinkForPathfinding link;
	private PathfindingBuilding pathfinding;
	
	public PathfindingThreadBuilding(LinkForPathfinding link){
		this.link = link;
		this.pathfinding = new PathfindingBuilding(link);
	}
	
	public synchronized void addBuilding(PositionBuilding building){
		buildingList2.add(building);
	}
	
	@Override
	public void run() {
		while(true){
			mergeList();
			update();
			try {
				Thread.sleep(15);
			} catch (InterruptedException e) {
				//Do nothing
			}
		}
	}

	private synchronized void mergeList() {
		buildingList.addAll(buildingList2);
		buildingList2.clear();
	}

	private void update() {
		int n = 0;
		while(buildingList.size() > 0 && n++ <4){
			PositionBuilding building = buildingList.remove(0);
			checkPath(building);
		}
	}
	
	private void checkPath(PositionBuilding building){
		long timeBefore = System.nanoTime();
		Path path = pathfinding.getPath(0, 0, link.getCastleX(), link.getCastleY(), GameData.noElement);
		if(path == null){
			link.removeBuilding(building);
			return;
		}
		
		link.addBuilding(building);
		long timeAfter = System.nanoTime();
		int time = (int) ((timeAfter - timeBefore)/(1000*1000));
		Log.g2("Time to check for paths : " + time );
		Log.k1("Time to check for paths : " + time );
	}

}
